package com.stars.services.impl.system;/**
 * Created by luodajie on 2019/1/5.
 */

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.stars.common.ObjectCopyUtils;
import com.stars.common.base.BaseConstant;
import com.stars.common.base.ResultMsg;
import com.stars.dao.mapper.system.SystemPermissionMapper;
import com.stars.entity.command.sys.SystemPermissionCommand;
import com.stars.entity.command.sys.SystemPermissionJsonCommand;
import com.stars.entity.sys.SystemPermission;
import com.stars.services.impl.BaseConfigServiceImpl;
import com.stars.services.system.PermissionConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author :dj
 * @version : 1.0.0
 * @description
 * @Date 2019-01-05 12:28
 * @note
 */
@Service
public class PermissionConfigServiceImpl extends
        BaseConfigServiceImpl<SystemPermissionMapper, SystemPermission> implements PermissionConfigService {
    @Autowired
    private SystemPermissionMapper systemPermissionMapper;

    @Override
    public ResultMsg permissionInsert(SystemPermissionCommand systemPermissionCommand) throws Exception {
        Map<String,String> map = new HashMap<>();
        //添加
        if(StringUtils.isNotBlank(systemPermissionCommand.getAddJson())){
            add(systemPermissionCommand,map);
        }
        //更新
        if(StringUtils.isNotBlank(systemPermissionCommand.getUpdateJson())){
            update(systemPermissionCommand,map);
        }
        //删除
        if(StringUtils.isNotBlank(systemPermissionCommand.getDelJson())){
            String [] ids = systemPermissionCommand.getDelJson().split(",");
           return deleteByIds(ids);
        }
        return ResultMsg.success();
    }

    /**
     * 添加其他菜单权限
     * @param jsonCommand
     * @return
     * @throws Exception
     */
    private void addMenu(SystemPermissionJsonCommand jsonCommand) throws Exception{
//        if(jsonCommand.getPerType().equals(BaseConstant.PER_CHILD) && jsonCommand.getPerBase()==1){
            //添加，编辑，删除
            String routing = jsonCommand.getPerUrl().replace("/","");

            SystemPermission menuAdd = new SystemPermission();
            menuAdd.setPerName("添加");
            menuAdd.setPerType(BaseConstant.PER_BTN);
            menuAdd.setPerIcon("md-add");
//            menuAdd.setPerBtnValid(routing+":create");
            menuAdd.setPid(jsonCommand.getId());
            systemPermissionMapper.insert(menuAdd);

            SystemPermission menuUpdate = new SystemPermission();
            menuUpdate.setPerName("编辑");
            menuUpdate.setPerType(BaseConstant.PER_BTN);
            menuUpdate.setPerIcon("md-create");
//            menuUpdate.setPerBtnValid(routing+":update");
            menuUpdate.setPid(jsonCommand.getId());
            systemPermissionMapper.insert(menuUpdate);

            SystemPermission menuDel = new SystemPermission();
            menuDel.setPerName("删除");
            menuDel.setPerType(BaseConstant.PER_BTN);
            menuDel.setPerIcon("md-trash");
//            menuDel.setPerBtnValid(routing+":delete");
            menuDel.setPid(jsonCommand.getId());
            insert(menuDel);
//        }
    }

    /**
     * 递归添加树形
     * @param addList
     * @param command
     */
    private void addParentId(SystemPermissionJsonCommand root,String parentId,List<SystemPermissionJsonCommand> addList,SystemPermissionCommand command, Map<String,String> map) throws Exception{
        for(SystemPermissionJsonCommand c:addList){
            if(root.getId().equals(c.getPid())){
                SystemPermission cc = toAddEntity(command, c);
                cc.setPid(parentId);
                if(StringUtils.isNotBlank(cc.getPerName())){
                    insert(cc);
                }
                map.put(c.getId(),cc.getId());
                addParentId(c,cc.getId(),addList,command,map);
            }
        }
    }


    @Override
    public ResultMsg permissionUpdate(SystemPermissionCommand command) throws Exception {
        SystemPermission systemPermission = systemPermissionMapper.selectByPrimaryKey(command.getId());
        if(null == systemPermission){
            return ResultMsg.failure("没有找到要修改的数据!");
        }
        ObjectCopyUtils.copyPropertiesIf(command,systemPermission, BaseConstant.EXCLUDES);
        systemPermissionMapper.updateByPrimaryKeySelective(systemPermission);
        return ResultMsg.success();
    }

    /**
     * 添加菜单数据
     * @param command
     * @param map
     * @throws Exception
     */
    private void add(SystemPermissionCommand command,Map<String,String> map) throws Exception{
        Gson gson = new Gson();
        List<SystemPermissionJsonCommand> addList= gson.fromJson(command.getAddJson(), new TypeToken<List<SystemPermissionJsonCommand>>() {}.getType());
        for (SystemPermissionJsonCommand add : addList) {
            //不包含Ext情况不往下走
            if(add.getPid().indexOf("Ext") ==-1){
                SystemPermission systemPermission = toAddEntity(command, add);
                if(StringUtils.isNotBlank(systemPermission.getPerName())){
                    insert(systemPermission);
                }
                map.put(add.getId(),systemPermission.getId());
                addParentId(add,systemPermission.getId(),addList,command,map);
            }
        }
    }

    private SystemPermission toAddEntity(SystemPermissionCommand command, SystemPermissionJsonCommand add) {
        SystemPermission systemResources = new SystemPermission();
        ObjectCopyUtils.copyPropertiesIf(add,systemResources, BaseConstant.ADD);
        if(StringUtils.isBlank(systemResources.getPerType())){
            systemResources.setPerType(BaseConstant.PER_BTN);
        }
        systemResources.setCreateId(command.getCreateId());
        systemResources.setCreateName(command.getCreateName());
        return systemResources;
    }

    /**
     * 更新菜单数据
     * @param command
     * @param map
     * @throws Exception
     */
    private void update(SystemPermissionCommand command,Map<String,String> map) throws Exception{
        Gson gson = new Gson();
        List<SystemPermissionJsonCommand> updateList= gson.fromJson(command.getUpdateJson(), new TypeToken<List<SystemPermissionJsonCommand>>() {}.getType());
        for (SystemPermissionJsonCommand updateTree : updateList) {
            SystemPermission systemPermission = systemPermissionMapper.selectByPrimaryKey(updateTree.getId());
            if(null == systemPermission){
                return;
            }
            ObjectCopyUtils.copyPropertiesIf(updateTree,systemPermission,BaseConstant.UPDATE);
            systemPermission.setLastUpdateId(command.getCreateId());
            systemPermission.setLastUpdateName(command.getCreateName());
            systemPermission.setLastUpdateDate(new Date());
            systemPermission.setPerIcon(updateTree.getPerIcon());
            systemPermission.setPerRoutingUrl(updateTree.getPerRoutingUrl());
            systemPermission.setPerUrl(updateTree.getPerUrl());
            systemPermission.setPerEnabled(updateTree.getPerEnabled());
            //如果包含ext ，不往下走
            if(StringUtils.isNotBlank(updateTree.getPid()) && updateTree.getPid().indexOf("Ext") ==0){
                //如果包含
                systemPermission.setPid(map.get(updateTree.getPid()));
            }
            if(StringUtils.isNotBlank(systemPermission.getPerName())){
                updateSelectiveById(systemPermission);
            }
        }
    }
}
